import { defineStore } from 'pinia'
import { 
  getAllArticles, 
  getArticle, 
  addArticle,
  likeArticle,
  unlikeArticle
} from '@/api/article'
import type { Article } from '@/models/article.model'

export const useArticleStore = defineStore('article', {
  state: () => ({
    articles: [] as Article[],
    article: null as Article | null,
    currentPage: 1,
    pageSize: 10,
    total: 0
  }),
  actions: {
    // 获取所有文章
    async fetchAllArticles(page = 1, size = 10) {
      try {
        const response = await getAllArticles()
        this.articles = response.data || []
        this.currentPage = page
        this.pageSize = size
        this.total = response.total || 0
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 获取单篇文章
    async fetchArticle(id: string) {
      try {
        const response = await getArticle(id)
        this.article = response
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 添加文章
    async addArticle(article: Article) {
      try {
        const response = await addArticle(article)
        this.articles.unshift(response)
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 点赞文章
    async likeArticle(id: string) {
      try {
        const response = await likeArticle(id)
        const articleIndex = this.articles.findIndex(item => item.id === id)
        if (articleIndex !== -1) {
          this.articles[articleIndex].likes = response.likes
        }
        if (this.article && this.article.id === id) {
          this.article.likes = response.likes
        }
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 取消点赞
    async unlikeArticle(id: string) {
      try {
        const response = await unlikeArticle(id)
        const articleIndex = this.articles.findIndex(item => item.id === id)
        if (articleIndex !== -1) {
          this.articles[articleIndex].likes = response.likes
        }
        if (this.article && this.article.id === id) {
          this.article.likes = response.likes
        }
        return response
      } catch (error) {
        throw error
      }
    }
  }
})